import os


def buildWgt(wgtPath, projectName, version):

    # 生成wgt包
    print("开始生成wgt包")

    # 有没有WGT文件夹 没有就创建
    if not os.path.exists(wgtPath):
        try:
            print(f"创建文件夹: {wgtPath}")
            os.makedirs(wgtPath)
        except Exception as e:
            print(f"创建文件夹时出错: {e}")
            exit(1)
    else:
        print(f"文件夹已存在: {wgtPath}")

    try:
        wgt_file_name = f"{projectName}WGT{version}.wgt"
        wgt_file_path = os.path.join(wgtPath, wgt_file_name)
        command = (
            "cli.exe publish --platform APP --type wgt --project "
            + projectName
            + " --path "
            + wgtPath
            + " --name "
            + projectName
            + "WGT"
            + ""
            + version
            + ".wgt"
        )
        exit_code = os.system(command)
    except Exception as e:
        print(f"生成WGT文件时出错: {e}")
        exit(1)

    if exit_code != 0:
        print("命令执行失败")
        exit(1)

    # 检查 WGT 文件是否生成
    if not os.path.exists(wgt_file_path):
        print(f"WGT 文件未生成: {wgt_file_path}")
        exit(1)
    else:
        print(f"WGT 文件已生成: {wgt_file_path}")
